package com.corpgovernment.common.handler;

import com.ctrip.corp.obt.generic.utils.EncryptUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Sm4TypeHandler implements TypeHandler<String> {

	private static String KEY = "1234567890123456";

	@Override
	public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
			throws SQLException {
		//防止为null时，创建XMLType出现错误
		if (StringUtils.isNotBlank(parameter)) {
			String encrypt = EncryptUtils.sm4Encrypt(parameter, KEY);
			ps.setObject(i, encrypt);
		} else {
			ps.setString(i, null);
		}
	}

	@Override
	public String getResult(ResultSet rs, String columnName) throws SQLException {
		String source = rs.getString(columnName);
		if (StringUtils.isNotBlank(source)) {
			return EncryptUtils.sm4Decrypt(source, KEY);
		} else {
			return null;
		}
	}

	@Override
	public String getResult(ResultSet rs, int columnIndex) throws SQLException {
		String source = rs.getString(columnIndex);
		if (StringUtils.isNotBlank(source)) {
			return EncryptUtils.sm4Decrypt(source, KEY);
		} else {
			return null;
		}
	}

	@Override
	public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
		String source = cs.getString(columnIndex);
		if (StringUtils.isNotBlank(source)) {
			return EncryptUtils.sm4Decrypt(source, KEY);
		} else {
			return null;
		}
	}
}
